//
//  TelephoneChargeViewModel.swift
//  zhonglb_iOS
//
//  Created by lxm on 2021/12/9.
//

import Foundation
class TelephoneChargeViewModel : BaseViewModel<Any> {
    static let CachePhoneInfoKey = "CachePhoneInfoKey"
    // 当前选中的套餐index
    var currentSelectIndex : BehaviorRelay<Int?> = BehaviorRelay(value: nil)
    // 套餐列表
    var mealList = BehaviorRelay(value: [TelePhoneModels.MealInfo]())
    // 当前电话查询信息
    var phoneInfo : BehaviorRelay<TelePhoneModels.PhoneInfo?> = BehaviorRelay(value: nil)
    // 配置信息
    var configInfo : BehaviorRelay<TelePhoneModels.ConfigInfo> = BehaviorRelay(value: TelePhoneModels.ConfigInfo())
    
    // 当前选中的套餐类型
    var currentType : BehaviorRelay<Int> = BehaviorRelay(value: 1)
    
    // 加载配置信息
    func laodConfigInfo() {
        showLoading.onNext(.show)
        TelephoneAPI.meal_list(["type" : "0"]).rxRequest(type: [TelePhoneModels.MealInfo].self).subscribe(onNext:{ [unowned self] resp in
            self.showLoading.onNext(.hide)
            var temp = self.mealList.value
            temp.append(contentsOf: resp)
            self.mealList.accept(temp)
        }, onError: { _ in
            self.showLoading.onNext(.showError)
        }).disposed(by: disposeBag)
        
        TelephoneAPI.meal_list(["type" : "1"]).rxRequest(type: [TelePhoneModels.MealInfo].self).subscribe(onNext:{ [unowned self] resp in
            self.showLoading.onNext(.hide)
            var temp = self.mealList.value
            temp.append(contentsOf: resp)
            self.mealList.accept(temp)
        }, onError: { _ in
            self.showLoading.onNext(.showError)
        }).disposed(by: disposeBag)
    }
        
    // 本地存入phone info
    func savePhoneInfo(phone : TelePhoneModels.PhoneInfo) {
        var r = getPhoneCache()
        if let exit = r.firstIndex(where: {$0.phone == phone.phone}) {
            r.remove(at: exit)
        }
        r.insert(phone, at: 0)
        while r.count > 3 {
            r.removeLast()
        }
        if let json = r.toJSONString() {
            UserDefaults.standard.set(json, forKey: TelephoneChargeViewModel.CachePhoneInfoKey)
            UserDefaults.standard.synchronize()
        }
    }
    
    // 获取本地存入
    func getPhoneCache() -> [TelePhoneModels.PhoneInfo] {
        var data = [TelePhoneModels.PhoneInfo]()
        if let json = UserDefaults.standard.object(forKey: TelephoneChargeViewModel.CachePhoneInfoKey) as? String, let r = [TelePhoneModels.PhoneInfo].deserialize(from: json)?.compactMap({$0}) {
            data = r
        }
        return data
    }
    
    // 删除某个缓存的信息
    func deletePhoneCache(phone : TelePhoneModels.PhoneInfo) {
        var r = getPhoneCache()
        if let exit = r.firstIndex(where: {$0.phone == phone.phone}) {
            r.remove(at: exit)
        }
        if let json = r.toJSONString() {
            UserDefaults.standard.set(json, forKey: TelephoneChargeViewModel.CachePhoneInfoKey)
            UserDefaults.standard.synchronize()
        }
    }
}
